import React from "react";
import {Link} from 'react-router-dom'
import logo from '../../images/logo.png'
import frame from '../../style/frame.less';

class MenuItem extends React.Component {

    constructor(props){
        super(props);
        this.state = {
            open : false
        }
    }

    toggle(){
       this.setState({
           open : !this.state.open
       });
    }

    routeChange(menuItem){
       if( menuItem.url && menuItem.url.length > 0 ){
           const {onMenuItemClick} = this.props;
           if( onMenuItemClick && typeof onMenuItemClick === "function"){
               onMenuItemClick(menuItem);
           }
       }
    }

    renderChild(){
        const {menuItem, level=1, ...props} = this.props;
        const hasChild = menuItem.childItem && menuItem.childItem.length > 0;
        if( !hasChild ){
            return;
        }
        const {open} = this.state;
        return (
            <ul className={`${frame.menuItemPanel} ${open ? frame.menuItemShow : frame.menuItemHidden}`}>
                {
                    menuItem.childItem.map((v, k)=>{
                        return (
                           <MenuItem key={"menu_" + level + "_" + k} menuItem={v} level={level + 1} {...props}/>
                        )
                    })
                }
            </ul>
        )
    }

    render() {
        const {menuItem, level = 1} = this.props;
        const hasChild = menuItem.childItem && menuItem.childItem.length > 0;
        const labelStyle = {paddingLeft : level * 20};
        return (
            <div className={frame.menuItem}>
                <div className={frame.menuItemLabel} onClick={this.toggle.bind(this)}>
                    {
                        menuItem.url && menuItem.url.length > 0 ?
                            (
                                <Link to={menuItem.url} className={frame.menuItemLabelText} style={labelStyle} onClick={this.routeChange.bind(this, menuItem)}>
                                    {menuItem.name}
                                </Link>
                            ):
                            (
                                <a className={frame.menuItemLabelText} style={labelStyle} href="javascript:;">
                                    {menuItem.name}
                                </a>
                            )
                    }
                    <span className={frame.itemIcon}>{ hasChild ? (this.state.open ? "-" : "+") : ""}</span>
                </div>
                {
                    this.renderChild()
                }
            </div>
        );
    }
}


export default MenuItem;
